#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称: doctor_consultation_api.py
完整存储路径: backend/api/admin/doctor_consultation_api.py
功能说明:
    医生交流管理API接口，用于医生和管理员查看并回复用户咨询
    
路由说明:
    - GET /api/admin/consultations - 获取咨询列表
    - GET /api/admin/consultations/<id> - 获取咨询详情
    - POST /api/admin/consultations/<id>/reply - 回复咨询
    - PUT /api/admin/consultations/<id>/assign - 分配医生
    - PUT /api/admin/consultations/<id>/status - 更新咨询状态
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from functools import wraps
from datetime import datetime
from backend.models.medical_consult import MedicalConsult
from backend.models.user import User
from backend.infrastructure.database import db
from backend.services.unified_log_service import log_service
from sqlalchemy import and_, or_

doctor_consultation_api = Blueprint('doctor_consultation_api', __name__)

# 管理员权限装饰器
def admin_required(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        from flask_jwt_extended import get_jwt
        claims = get_jwt()
        roles = claims.get('roles', [])
        if 'admin' not in roles and 'doctor' not in roles:
            return jsonify({'success': False, 'message': '仅管理员或医生可操作'}), 403
        return fn(*args, **kwargs)
    return wrapper

@doctor_consultation_api.route('/api/admin/consultations', methods=['GET'])
@jwt_required()
@admin_required
def list_consultations():
    """获取咨询列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        status = request.args.get('status')
        category = request.args.get('category')
        priority = request.args.get('priority')
        assigned_doctor = request.args.get('assigned_doctor', type=int)
        search_term = request.args.get('search', '').strip()
        
        # 构建查询
        query = MedicalConsult.query
        
        # 状态筛选
        if status:
            query = query.filter(MedicalConsult.status == status)
        
        # 分类筛选
        if category:
            query = query.filter(MedicalConsult.category == category)
        
        # 优先级筛选
        if priority:
            query = query.filter(MedicalConsult.priority == priority)
        
        # 指定医生筛选
        if assigned_doctor:
            query = query.filter(MedicalConsult.doctor_id == assigned_doctor)
        
        # 搜索功能
        if search_term:
            query = query.join(User).filter(
                or_(
                    MedicalConsult.title.like(f'%{search_term}%'),
                    MedicalConsult.content.like(f'%{search_term}%'),
                    User.name.like(f'%{search_term}%')
                )
            )
        
        # 分页查询
        pagination = query.order_by(MedicalConsult.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        consultations = []
        for consult in pagination.items:
            consult_dict = consult.to_dict()
            
            # 添加用户信息
            if consult.user:
                consult_dict['user_name'] = consult.user.name
                consult_dict['user_phone'] = consult.user.mobile
            
            # 添加指定医生信息
            if consult.doctor:
                consult_dict['assigned_doctor_name'] = consult.doctor.name
            
            consultations.append(consult_dict)
        
        return jsonify({
            'success': True,
            'data': {
                'consultations': consultations,
                'pagination': {
                    'page': page,
                    'per_page': per_page,
                    'total': pagination.total,
                    'pages': pagination.pages,
                    'has_next': pagination.has_next,
                    'has_prev': pagination.has_prev
                }
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取咨询列表失败: {str(e)}'
        }), 500

@doctor_consultation_api.route('/api/admin/consultations/<int:consult_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_consultation_detail(consult_id):
    """获取咨询详情"""
    try:
        consultation = MedicalConsult.query.get_or_404(consult_id)
        
        consult_dict = consultation.to_dict()
        
        # 添加用户详细信息
        if consultation.user:
            consult_dict['user_info'] = {
                'id': consultation.user.id,
                'name': consultation.user.name,
                'phone': consultation.user.mobile,
                'email': consultation.user.email
            }
        
        # 添加指定医生信息
        if consultation.doctor:
            consult_dict['assigned_doctor_info'] = {
                'id': consultation.doctor.id,
                'name': consultation.doctor.name,
                'speciality': getattr(consultation.doctor, 'speciality', ''),
                'title': getattr(consultation.doctor, 'title', '')
            }
        
        return jsonify({
            'success': True,
            'data': consult_dict
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取咨询详情失败: {str(e)}'
        }), 500

@doctor_consultation_api.route('/api/admin/consultations/<int:consult_id>/reply', methods=['POST'])
@jwt_required()
@admin_required
def reply_consultation(consult_id):
    """回复用户咨询"""
    try:
        consultation = MedicalConsult.query.get_or_404(consult_id)
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        if not data.get('reply_content'):
            return jsonify({
                'success': False,
                'message': '回复内容不能为空'
            }), 400
        
        # 更新咨询记录
        consultation.reply_content = data['reply_content']
        consultation.replied_at = datetime.utcnow()
        consultation.replied_by = current_user_id
        consultation.status = 'replied'
        
        # 如果提供了诊断建议
        if data.get('diagnosis'):
            consultation.diagnosis = data['diagnosis']
        
        # 如果提供了治疗建议
        if data.get('treatment_advice'):
            consultation.treatment_advice = data['treatment_advice']
        
        # 如果提供了随访建议
        if data.get('followup_advice'):
            consultation.followup_advice = data['followup_advice']
        
        consultation.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='REPLY',
            table_name='medical_consults',
            record_id=consult_id,
            details=f'回复咨询: {consultation.title}'
        )
        
        # TODO: 这里可以发送邮件或推送通知给用户
        
        return jsonify({
            'success': True,
            'data': consultation.to_dict(),
            'message': '回复成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'回复失败: {str(e)}'
        }), 500

@doctor_consultation_api.route('/api/admin/consultations/<int:consult_id>/assign', methods=['PUT'])
@jwt_required()
@admin_required
def assign_doctor(consult_id):
    """分配医生"""
    try:
        consultation = MedicalConsult.query.get_or_404(consult_id)
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        doctor_id = data.get('doctor_id')
        if not doctor_id:
            return jsonify({
                'success': False,
                'message': '请选择要分配的医生'
            }), 400
        
        # 验证医生是否存在
        doctor = User.query.filter_by(id=doctor_id).first()
        if not doctor:
            return jsonify({
                'success': False,
                'message': '指定的医生不存在'
            }), 400
        
        # 更新分配信息
        old_doctor_id = consultation.doctor_id
        consultation.doctor_id = doctor_id
        consultation.assigned_at = datetime.utcnow()
        consultation.updated_at = datetime.utcnow()
        
        # 如果咨询状态是待处理，更新为处理中
        if consultation.status == 'pending':
            consultation.status = 'in_progress'
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='ASSIGN',
            table_name='medical_consults',
            record_id=consult_id,
            details=f'分配咨询给医生: {doctor.name}'
        )
        
        return jsonify({
            'success': True,
            'data': consultation.to_dict(),
            'message': f'已分配给医生: {doctor.name}'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'分配失败: {str(e)}'
        }), 500

@doctor_consultation_api.route('/api/admin/consultations/<int:consult_id>/status', methods=['PUT'])
@jwt_required()
@admin_required
def update_consultation_status(consult_id):
    """更新咨询状态"""
    try:
        consultation = MedicalConsult.query.get_or_404(consult_id)
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        new_status = data.get('status')
        if not new_status:
            return jsonify({
                'success': False,
                'message': '状态不能为空'
            }), 400
        
        # 验证状态值
        valid_statuses = ['pending', 'in_progress', 'replied', 'closed']
        if new_status not in valid_statuses:
            return jsonify({
                'success': False,
                'message': '无效的状态值'
            }), 400
        
        old_status = consultation.status
        consultation.status = new_status
        consultation.updated_at = datetime.utcnow()
        
        # 如果状态变为已关闭，记录关闭时间
        if new_status == 'closed':
            consultation.closed_at = datetime.utcnow()
            consultation.closed_by = current_user_id
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='UPDATE_STATUS',
            table_name='medical_consults',
            record_id=consult_id,
            details=f'咨询状态从 {old_status} 更改为 {new_status}'
        )
        
        return jsonify({
            'success': True,
            'data': consultation.to_dict(),
            'message': '状态更新成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'更新状态失败: {str(e)}'
        }), 500

@doctor_consultation_api.route('/api/admin/consultations/statistics', methods=['GET'])
@jwt_required()
@admin_required
def get_consultation_statistics():
    """获取咨询统计信息"""
    try:
        # 按状态统计
        statuses = ['pending', 'in_progress', 'replied', 'closed']
        status_stats = {}
        for status in statuses:
            count = MedicalConsult.query.filter_by(status=status).count()
            status_stats[status] = count
        
        # 按分类统计
        categories = ['vision_check', 'intervention', 'symptoms', 'treatment', 'prevention', 'other']
        category_stats = {}
        for category in categories:
            count = MedicalConsult.query.filter_by(category=category).count()
            category_stats[category] = count
        
        # 按优先级统计
        priorities = ['low', 'normal', 'high', 'urgent']
        priority_stats = {}
        for priority in priorities:
            count = MedicalConsult.query.filter_by(priority=priority).count()
            priority_stats[priority] = count
        
        # 本月新增咨询数量
        from datetime import datetime, timedelta
        current_month = datetime.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        monthly_count = MedicalConsult.query.filter(MedicalConsult.created_at >= current_month).count()
        
        # 待处理咨询数量
        pending_count = MedicalConsult.query.filter_by(status='pending').count()
        
        # 医生工作量统计（本月）
        doctor_stats = db.session.query(
            User.id,
            User.name,
            db.func.count(MedicalConsult.id).label('consult_count')
        ).join(
            MedicalConsult, User.id == MedicalConsult.doctor_id
        ).filter(
            MedicalConsult.created_at >= current_month
        ).group_by(
            User.id, User.name
        ).all()
        
        doctor_workload = [
            {
                'doctor_id': stat.id,
                'doctor_name': stat.name,
                'consult_count': stat.consult_count
            }
            for stat in doctor_stats
        ]
        
        return jsonify({
            'success': True,
            'data': {
                'status_statistics': status_stats,
                'category_statistics': category_stats,
                'priority_statistics': priority_stats,
                'monthly_count': monthly_count,
                'pending_count': pending_count,
                'total_count': sum(status_stats.values()),
                'doctor_workload': doctor_workload
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取统计信息失败: {str(e)}'
        }), 500

@doctor_consultation_api.route('/api/admin/doctors', methods=['GET'])
@jwt_required()
@admin_required
def list_doctors():
    """获取医生列表（用于分配选择）"""
    try:
        # 查询具有医生角色的用户
        doctors = User.query.filter(
            User.roles.any(name='doctor')
        ).all()
        
        doctor_list = []
        for doctor in doctors:
            # 统计医生当前处理的咨询数量
            active_consults = MedicalConsult.query.filter(
                and_(
                    MedicalConsult.doctor_id == doctor.id,
                    MedicalConsult.status.in_(['pending', 'replied'])
                )
            ).count()
            
            doctor_list.append({
                'id': doctor.id,
                'name': doctor.name,
                'email': doctor.email,
                'speciality': getattr(doctor, 'speciality', ''),
                'title': getattr(doctor, 'title', ''),
                'active_consults': active_consults
            })
        
        return jsonify({
            'success': True,
            'data': {
                'doctors': doctor_list
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取医生列表失败: {str(e)}'
        }), 500

@doctor_consultation_api.route('/api/admin/consultations/stats', methods=['GET'])
@jwt_required()
@admin_required
def get_consultation_stats():
    """获取咨询统计信息"""
    try:
        # 按状态统计
        pending_count = MedicalConsult.query.filter_by(status='pending').count()
        replied_count = MedicalConsult.query.filter_by(status='replied').count()
        closed_count = MedicalConsult.query.filter_by(status='closed').count()
        
        # 活跃医生数量（有分配咨询的医生）
        active_doctors = db.session.query(MedicalConsult.doctor_id).filter(
            MedicalConsult.doctor_id.isnot(None)
        ).distinct().count()
        
        # 今日咨询数量
        from datetime import date
        today = date.today()
        today_count = MedicalConsult.query.filter(
            db.func.date(MedicalConsult.created_at) == today
        ).count()
        
        return jsonify({
            'success': True,
            'data': {
                'pending': pending_count,
                'replied': replied_count,
                'closed': closed_count,
                'active_doctors': active_doctors,
                'today': today_count
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取统计信息失败: {str(e)}'
        }), 500

@doctor_consultation_api.route('/api/admin/doctors', methods=['GET'])
@jwt_required()
@admin_required
def get_doctors_list():
    """获取医生列表"""
    try:
        # 获取所有医生角色的用户
        from backend.models.role import Role
        doctor_role = Role.query.filter_by(name='doctor').first()
        doctors = []
        
        if doctor_role:
            doctors = doctor_role.users.all()
        
        doctor_list = []
        for doctor in doctors:
            doctor_list.append({
                'id': doctor.id,
                'name': doctor.name,
                'email': doctor.email or '',
                'specialty': getattr(doctor, 'department', '') or '全科',
            })
        
        return jsonify({
            'success': True,
            'data': doctor_list
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取医生列表失败: {str(e)}'
        }), 500
